﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using Com.DAO;

namespace WF.Web.Attachment
{
    public partial class UploadAttachment : BasePage
    {
        public Com.DAO.DataManager mobjDB = new DataManager();
        public string KQApplyID;

        protected void Page_Load(object sender, EventArgs e)
        {
            KQApplyID = Request.QueryString.Get("KQAPPLYID");
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            try
            {
                if (InputFile1.FileName == string.Empty)
                //if (this.fileUpload.FileName == "")
                {
                    throw new Exception("请选择需要上传的图片");
                }

                if (KQApplyID == string.Empty)
                {
                    throw new Exception("没有单据ID!");
                }

                string filetype = Path.GetExtension(this.InputFile1.FileName);
                //string filetype = Path.GetExtension(this.fileUpload.FileName);
                if (filetype.ToLower() != ".jpg" && filetype.ToLower() != ".png" && filetype.ToLower() != ".gif")
                {
                    throw new Exception("目前只能上传.jpg,.png或者.gif格式的图片文件!");
                }

                string imageID = this.SaveImageInfo();

                this.ShowAjaxMessage("图片上传成功!", true, false);
            }
            catch (Exception ex)
            {
                this.ShowAjaxMessage(ex);
            }
        }

        private string SaveImageInfo()
        {
            string strTmpFilePath = string.Empty;
            try
            {
                string imgID = this.GetNewGUID();

                int imageLength = (int)InputFile1.ContentLength;
                //int imageLength = fileUpload.PostedFile.ContentLength;
                //图片数据
                byte[] imageByteArray = new byte[imageLength];

                //上传图片至临时文件

                string strTmpFileName = string.Format("../Upload/{0}", this.GetNewGUID());
                strTmpFilePath = Server.MapPath(strTmpFileName);
                InputFile1.MoveTo(strTmpFilePath, Brettle.Web.NeatUpload.MoveToOptions.Overwrite);

                FileStream fileStream = new FileStream(strTmpFilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
                byte[] bytes = new byte[fileStream.Length];
                fileStream.Read(bytes, 0, bytes.Length);
                fileStream.Close();
                // 把 byte[] 转换成 Stream 
                Stream imageStream = new MemoryStream(bytes);

                //Stream imageStream = fileUpload.PostedFile.InputStream;
                imageStream.Read(imageByteArray, 0, imageLength);

                Bitmap image = (Bitmap)System.Drawing.Bitmap.FromStream(imageStream);

                //gsl
                //imageByteArray = this.ZoomBmp(image, imageByteArray);



                //读取ThumbData
                Byte[] thumbData = imageByteArray;
                //int thumbSize = 0;

                //System.Drawing.Image img = System.Drawing.Image.FromStream(imageStream);
                //System.Drawing.Image thumbImage = img.GetThumbnailImage(200, 200, null, System.IntPtr.Zero);
                //System.IO.MemoryStream imageThumbStream = new System.IO.MemoryStream();
                //thumbImage.Save(imageThumbStream, img.RawFormat);
                //thumbSize = Convert.ToInt32(imageThumbStream.Length);
                //thumbData = new Byte[thumbSize];
                //imageThumbStream.Position = 0;
                //imageThumbStream.Read(thumbData, 0, thumbSize);
                thumbData = this.GetThumbImage(image, thumbData);



                string sql = "insert into dbo.Attachment (ID,EntityType,EntityID,[FileName],ImageThumbData,FileContent,Description,UploadDate,UploadEmpID) values(@ID,@EntityType,@EntityID,@FileName,@ImageThumbData,@FileContent,@Description,@UploadDate,@UploadEmpID)";

                this.mobjDB.OpenWithConfig();
                SqlCommand sqlcom = new SqlCommand(sql, this.mobjDB.Connection());
                sqlcom.Parameters.AddWithValue("@ID", imgID);
                sqlcom.Parameters.AddWithValue("@EntityType", "Photo");
                sqlcom.Parameters.AddWithValue("@EntityID", KQApplyID);
                sqlcom.Parameters.AddWithValue("@FileName", Path.GetExtension(InputFile1.FileName));//取得文件扩展名    
                //sqlcom.Parameters.AddWithValue("@ImageContentType", Path.GetExtension(fileUpload.PostedFile.FileName));//取得文件扩展名    
                sqlcom.Parameters.AddWithValue("@ImageThumbData", thumbData);
                sqlcom.Parameters.AddWithValue("@FileContent", imageByteArray);
                //sqlcom.Parameters.AddWithValue("@FileName", Path.GetFileName(fileUpload.PostedFile.FileName));
                sqlcom.Parameters.AddWithValue("@Description", imageLength);
                sqlcom.Parameters.AddWithValue("@UploadDate", DateTime.Now);
                sqlcom.Parameters.AddWithValue("@UploadEmpID", "5d1e4314-c9de-4434-bce0-a1eab0cd9e38");
                sqlcom.ExecuteNonQuery();
                this.mobjDB.Close();

                return imgID;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (System.IO.File.Exists(strTmpFilePath))//删除临时文件
                {
                    System.IO.File.Delete(strTmpFilePath);
                }
            }
        }

        private string GetNewGUID()
        {
            string rtn = System.Guid.NewGuid().ToString();

            try
            {
                string strDateTime = null;
                string strID = null;
                long i = 0;
                int r = 0;

                rtn = rtn.Replace("-", "").ToUpper();
                strDateTime = System.DateTime.Now.ToString("yyyyMMddHHmmss");

                strID = "";
                Random rnd = new Random();

                for (i = 1; i <= 18; i++)
                {
                    r = ((int)(16 * rnd.NextDouble()));
                    strID = strID + r.ToString("x1");
                }

                rtn = strDateTime + rtn.Substring(14);
            }
            catch
            {
            }
            return rtn;
        }

        private Byte[] ZoomBmp(Bitmap image, Byte[] imageByteArray)
        {
            int maxWidth = 1024;
            if (image.Width > maxWidth || image.Height > maxWidth)
            {
                int newWidth = 0;
                int newHeight = 0;

                if (image.Width > image.Height)
                {
                    newWidth = maxWidth;
                    newHeight = image.Height * maxWidth / image.Width;
                }
                else
                {
                    newHeight = maxWidth;
                    newWidth = image.Width * maxWidth / image.Height;
                }
                //Bitmap newImage = new Bitmap(image, newWidth, newHeight);
                System.Drawing.Image newImage = image.GetThumbnailImage(newWidth, newHeight, null, System.IntPtr.Zero);

                MemoryStream mStream = new MemoryStream();
                newImage.Save(mStream, image.RawFormat);
                int imageLength = (int)mStream.Length;
                imageByteArray = new Byte[imageLength];
                mStream.Position = 0;
                mStream.Read(imageByteArray, 0, imageLength);
            }
            return imageByteArray;
        }

        private Byte[] GetThumbImage(Bitmap image, Byte[] imageByteArray)
        {
            int maxWidth = 200;
            if (image.Width > maxWidth || image.Height > maxWidth)
            {
                int newWidth = 0;
                int newHeight = 0;

                if (image.Width > image.Height)
                {
                    newWidth = maxWidth;
                    newHeight = image.Height * maxWidth / image.Width;
                }
                else
                {
                    newHeight = maxWidth;
                    newWidth = image.Width * maxWidth / image.Height;
                }
                //Bitmap newImage = new Bitmap(image, newWidth, newHeight);
                System.Drawing.Image newImage = image.GetThumbnailImage(newWidth, newHeight, null, System.IntPtr.Zero);

                MemoryStream mStream = new MemoryStream();
                newImage.Save(mStream, image.RawFormat);
                int imageLength = (int)mStream.Length;
                imageByteArray = new Byte[imageLength];
                mStream.Position = 0;
                mStream.Read(imageByteArray, 0, imageLength);
            }
            return imageByteArray;
        }
    }
}